/*
 * The MIT License
 *
 * Copyright 2011 Edwin Bratini <edwin.bratini@gmail.com>.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

/*
 * RegistroEdicionCaso.java
 *
 * Created on Nov 10, 2011, 10:18:30 AM
 */
package org.salvador_dali.psychsys.ui;

import java.awt.Color;
import java.awt.Toolkit;
import java.util.Date;
import java.util.HashMap;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import org.salvador_dali.psychsys.business.validators.DateFieldValidator;
import org.salvador_dali.psychsys.business.DateUtils;
import org.salvador_dali.psychsys.business.validators.EmptyFieldValidator;
import org.salvador_dali.psychsys.business.EntitySearcher;
import org.salvador_dali.psychsys.business.validators.FieldValidator;
import org.salvador_dali.psychsys.business.validators.FormFieldValidator;
import org.salvador_dali.psychsys.business.jpa_controllers.CasoJpaDao;
import org.salvador_dali.psychsys.business.jpa_controllers.ReferimientoJpaDao;
import org.salvador_dali.psychsys.model.entities.Caso;
import org.salvador_dali.psychsys.model.entities.Referimiento;

/**
 *
 * @author Edwin Bratini <edwin.bratini@gmail.com>
 */
public class RegistroEdicionCaso extends javax.swing.JFrame {
    
    private RegistroEdicionModo modo = RegistroEdicionModo.REGISTRO;
    private CasoJpaDao jpaCasoDao = new CasoJpaDao();
    private Referimiento referimientoCaso;
    private Caso casoAEditar;

    /** Creates new form RegistroEdicionCaso */
    public RegistroEdicionCaso() {
        initComponents();
    }
    
    public RegistroEdicionCaso(RegistroEdicionModo modo) {
        this();
        this.modo = modo;
    }
    
    public RegistroEdicionModo getModo() {
        return modo;
    }
    
    public void setModo(RegistroEdicionModo modo) {
        this.modo = modo;
    }
    
    public Caso getCasoAEditar() {
        return casoAEditar;
    }
    
    public void setCasoAEditar(Caso casoAEditar) {
        this.casoAEditar = casoAEditar;
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        bgpDefinitivo = new javax.swing.ButtonGroup();
        statusPanel = new javax.swing.JPanel();
        javax.swing.JSeparator statusPanelSeparator = new javax.swing.JSeparator();
        statusMessageLabel = new javax.swing.JLabel();
        statusAnimationLabel = new javax.swing.JLabel();
        btnAceptar = new javax.swing.JButton();
        btnCancelar = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        lblFecha = new javax.swing.JLabel();
        ftfFecha = new javax.swing.JFormattedTextField();
        lblAnioEscolar = new javax.swing.JLabel();
        ftfAnioEscolar = new javax.swing.JFormattedTextField();
        lblReferimiento = new javax.swing.JLabel();
        txtReferimiento = new javax.swing.JTextField();
        lblFechaValMarker = new javax.swing.JLabel();
        lblAnioEscolarValMarker = new javax.swing.JLabel();
        lblReferimientoValMarker = new javax.swing.JLabel();
        btnBuscar = new javax.swing.JButton();
        lblEstadoCaso = new javax.swing.JLabel();
        cmbEstadoCaso = new javax.swing.JComboBox();
        pnlDetallesCaso = new javax.swing.JPanel();
        jSplitPane1 = new javax.swing.JSplitPane();
        jScrollPane1 = new javax.swing.JScrollPane();
        lstDetallesCaso = new javax.swing.JList();
        lpnDetallesCaso = new javax.swing.JLayeredPane();
        pnlAnalisisResPruebas = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        txaAnalisisResPruebas = new javax.swing.JTextArea();
        pnlJuicioClinico = new javax.swing.JPanel();
        jScrollPane3 = new javax.swing.JScrollPane();
        txaJuicioClinico = new javax.swing.JTextArea();
        pnlDiagnostico = new javax.swing.JPanel();
        jScrollPane4 = new javax.swing.JScrollPane();
        txaDiagnostico = new javax.swing.JTextArea();
        pnlDefinitivo = new javax.swing.JPanel();
        rbnDiagDefSi = new javax.swing.JRadioButton();
        rbnDiagDefNo = new javax.swing.JRadioButton();
        pnlTratamiento = new javax.swing.JPanel();
        jScrollPane5 = new javax.swing.JScrollPane();
        txaTratamiento = new javax.swing.JTextArea();
        pnlResumenEvolucion = new javax.swing.JPanel();
        jScrollPane6 = new javax.swing.JScrollPane();
        txaResumenEvolucion = new javax.swing.JTextArea();
        pnlRecomendaciones = new javax.swing.JPanel();
        jScrollPane7 = new javax.swing.JScrollPane();
        txaRecomendaciones = new javax.swing.JTextArea();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Registrar Caso");
        setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("/resources/images/psych logo.png")));
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        statusMessageLabel.setForeground(new java.awt.Color(0, 153, 51));
        statusMessageLabel.setText("Caso registrado exitosamente.");

        statusAnimationLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        statusAnimationLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/images/circle progress bar 20x20.png"))); // NOI18N

        javax.swing.GroupLayout statusPanelLayout = new javax.swing.GroupLayout(statusPanel);
        statusPanel.setLayout(statusPanelLayout);
        statusPanelLayout.setHorizontalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(statusPanelSeparator, javax.swing.GroupLayout.DEFAULT_SIZE, 433, Short.MAX_VALUE)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(statusMessageLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 245, Short.MAX_VALUE)
                .addComponent(statusAnimationLabel)
                .addContainerGap())
        );
        statusPanelLayout.setVerticalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addComponent(statusPanelSeparator, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(statusMessageLabel)
                    .addComponent(statusAnimationLabel))
                .addContainerGap())
        );

        btnAceptar.setText("Aceptar");
        btnAceptar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAceptarActionPerformed(evt);
            }
        });

        btnCancelar.setText("Cancelar");
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });

        jPanel2.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        lblFecha.setText("Fecha");

        try {
            ftfFecha.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##-##-####")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }

        lblAnioEscolar.setText("Año Escolar");

        try {
            ftfAnioEscolar.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("####-####")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }

        lblReferimiento.setText("Referemiento");

        txtReferimiento.setEditable(false);

        lblFechaValMarker.setForeground(new java.awt.Color(255, 51, 51));
        lblFechaValMarker.setLabelFor(ftfFecha);

        lblAnioEscolarValMarker.setForeground(new java.awt.Color(255, 51, 51));
        lblAnioEscolarValMarker.setLabelFor(ftfAnioEscolar);

        lblReferimientoValMarker.setForeground(new java.awt.Color(255, 51, 51));
        lblReferimientoValMarker.setLabelFor(txtReferimiento);

        btnBuscar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/images/detalles.png"))); // NOI18N
        btnBuscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnBuscarActionPerformed(evt);
            }
        });

        lblEstadoCaso.setText("Estado del Caso");

        cmbEstadoCaso.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Abierto", "Cerrado", "Pendiente" }));

        pnlDetallesCaso.setBorder(javax.swing.BorderFactory.createTitledBorder("Detalles Caso"));

        jSplitPane1.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);
        jSplitPane1.setEnabled(false);

        lstDetallesCaso.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Analisis Resultados Pruebas Aplicadas", "Juicio Clinico", "Diagnostico", "Tratamiento", "Resumen Evolucion", "Recomendaciones" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        lstDetallesCaso.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        lstDetallesCaso.setVisibleRowCount(6);
        lstDetallesCaso.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                lstDetallesCasoValueChanged(evt);
            }
        });
        jScrollPane1.setViewportView(lstDetallesCaso);

        jSplitPane1.setTopComponent(jScrollPane1);

        pnlAnalisisResPruebas.setBorder(javax.swing.BorderFactory.createTitledBorder("Analisis Resultados Pruebas Aplicadas"));

        txaAnalisisResPruebas.setColumns(20);
        txaAnalisisResPruebas.setLineWrap(true);
        txaAnalisisResPruebas.setRows(5);
        txaAnalisisResPruebas.setWrapStyleWord(true);
        jScrollPane2.setViewportView(txaAnalisisResPruebas);

        javax.swing.GroupLayout pnlAnalisisResPruebasLayout = new javax.swing.GroupLayout(pnlAnalisisResPruebas);
        pnlAnalisisResPruebas.setLayout(pnlAnalisisResPruebasLayout);
        pnlAnalisisResPruebasLayout.setHorizontalGroup(
            pnlAnalisisResPruebasLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 378, javax.swing.GroupLayout.PREFERRED_SIZE)
        );
        pnlAnalisisResPruebasLayout.setVerticalGroup(
            pnlAnalisisResPruebasLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 223, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        pnlAnalisisResPruebas.setBounds(0, 0, 394, 247);
        lpnDetallesCaso.add(pnlAnalisisResPruebas, javax.swing.JLayeredPane.DEFAULT_LAYER);

        pnlJuicioClinico.setBorder(javax.swing.BorderFactory.createTitledBorder("Juicio Clinico"));

        txaJuicioClinico.setColumns(20);
        txaJuicioClinico.setLineWrap(true);
        txaJuicioClinico.setRows(5);
        txaJuicioClinico.setWrapStyleWord(true);
        jScrollPane3.setViewportView(txaJuicioClinico);

        javax.swing.GroupLayout pnlJuicioClinicoLayout = new javax.swing.GroupLayout(pnlJuicioClinico);
        pnlJuicioClinico.setLayout(pnlJuicioClinicoLayout);
        pnlJuicioClinicoLayout.setHorizontalGroup(
            pnlJuicioClinicoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 378, javax.swing.GroupLayout.PREFERRED_SIZE)
        );
        pnlJuicioClinicoLayout.setVerticalGroup(
            pnlJuicioClinicoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 223, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        pnlJuicioClinico.setBounds(0, 0, 390, 250);
        lpnDetallesCaso.add(pnlJuicioClinico, javax.swing.JLayeredPane.DEFAULT_LAYER);

        pnlDiagnostico.setBorder(javax.swing.BorderFactory.createTitledBorder("Diagnostico"));

        txaDiagnostico.setColumns(20);
        txaDiagnostico.setLineWrap(true);
        txaDiagnostico.setRows(5);
        txaDiagnostico.setWrapStyleWord(true);
        jScrollPane4.setViewportView(txaDiagnostico);

        pnlDefinitivo.setBorder(javax.swing.BorderFactory.createTitledBorder("Definitivo"));

        bgpDefinitivo.add(rbnDiagDefSi);
        rbnDiagDefSi.setText("Si");

        bgpDefinitivo.add(rbnDiagDefNo);
        rbnDiagDefNo.setSelected(true);
        rbnDiagDefNo.setText("No");

        javax.swing.GroupLayout pnlDefinitivoLayout = new javax.swing.GroupLayout(pnlDefinitivo);
        pnlDefinitivo.setLayout(pnlDefinitivoLayout);
        pnlDefinitivoLayout.setHorizontalGroup(
            pnlDefinitivoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlDefinitivoLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(rbnDiagDefSi)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(rbnDiagDefNo)
                .addContainerGap(286, Short.MAX_VALUE))
        );
        pnlDefinitivoLayout.setVerticalGroup(
            pnlDefinitivoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlDefinitivoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(rbnDiagDefSi)
                .addComponent(rbnDiagDefNo))
        );

        javax.swing.GroupLayout pnlDiagnosticoLayout = new javax.swing.GroupLayout(pnlDiagnostico);
        pnlDiagnostico.setLayout(pnlDiagnosticoLayout);
        pnlDiagnosticoLayout.setHorizontalGroup(
            pnlDiagnosticoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(pnlDefinitivo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 378, javax.swing.GroupLayout.PREFERRED_SIZE)
        );
        pnlDiagnosticoLayout.setVerticalGroup(
            pnlDiagnosticoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnlDiagnosticoLayout.createSequentialGroup()
                .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 156, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(pnlDefinitivo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        pnlDiagnostico.setBounds(0, 0, 390, 250);
        lpnDetallesCaso.add(pnlDiagnostico, javax.swing.JLayeredPane.DEFAULT_LAYER);

        pnlTratamiento.setBorder(javax.swing.BorderFactory.createTitledBorder("Tratamiento"));

        txaTratamiento.setColumns(20);
        txaTratamiento.setLineWrap(true);
        txaTratamiento.setRows(5);
        txaTratamiento.setWrapStyleWord(true);
        jScrollPane5.setViewportView(txaTratamiento);

        javax.swing.GroupLayout pnlTratamientoLayout = new javax.swing.GroupLayout(pnlTratamiento);
        pnlTratamiento.setLayout(pnlTratamientoLayout);
        pnlTratamientoLayout.setHorizontalGroup(
            pnlTratamientoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane5, javax.swing.GroupLayout.PREFERRED_SIZE, 378, javax.swing.GroupLayout.PREFERRED_SIZE)
        );
        pnlTratamientoLayout.setVerticalGroup(
            pnlTratamientoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane5, javax.swing.GroupLayout.PREFERRED_SIZE, 223, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        pnlTratamiento.setBounds(0, 0, 390, 250);
        lpnDetallesCaso.add(pnlTratamiento, javax.swing.JLayeredPane.DEFAULT_LAYER);

        pnlResumenEvolucion.setBorder(javax.swing.BorderFactory.createTitledBorder("Resumen Evolucion"));

        txaResumenEvolucion.setColumns(20);
        txaResumenEvolucion.setLineWrap(true);
        txaResumenEvolucion.setRows(5);
        txaResumenEvolucion.setWrapStyleWord(true);
        jScrollPane6.setViewportView(txaResumenEvolucion);

        javax.swing.GroupLayout pnlResumenEvolucionLayout = new javax.swing.GroupLayout(pnlResumenEvolucion);
        pnlResumenEvolucion.setLayout(pnlResumenEvolucionLayout);
        pnlResumenEvolucionLayout.setHorizontalGroup(
            pnlResumenEvolucionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane6, javax.swing.GroupLayout.PREFERRED_SIZE, 378, javax.swing.GroupLayout.PREFERRED_SIZE)
        );
        pnlResumenEvolucionLayout.setVerticalGroup(
            pnlResumenEvolucionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane6, javax.swing.GroupLayout.PREFERRED_SIZE, 223, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        pnlResumenEvolucion.setBounds(0, 0, 390, 250);
        lpnDetallesCaso.add(pnlResumenEvolucion, javax.swing.JLayeredPane.DEFAULT_LAYER);

        pnlRecomendaciones.setBorder(javax.swing.BorderFactory.createTitledBorder("Recomendaciones"));

        txaRecomendaciones.setColumns(20);
        txaRecomendaciones.setLineWrap(true);
        txaRecomendaciones.setRows(5);
        txaRecomendaciones.setWrapStyleWord(true);
        jScrollPane7.setViewportView(txaRecomendaciones);

        javax.swing.GroupLayout pnlRecomendacionesLayout = new javax.swing.GroupLayout(pnlRecomendaciones);
        pnlRecomendaciones.setLayout(pnlRecomendacionesLayout);
        pnlRecomendacionesLayout.setHorizontalGroup(
            pnlRecomendacionesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane7, javax.swing.GroupLayout.PREFERRED_SIZE, 378, javax.swing.GroupLayout.PREFERRED_SIZE)
        );
        pnlRecomendacionesLayout.setVerticalGroup(
            pnlRecomendacionesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane7, javax.swing.GroupLayout.PREFERRED_SIZE, 223, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        pnlRecomendaciones.setBounds(0, 0, 390, 250);
        lpnDetallesCaso.add(pnlRecomendaciones, javax.swing.JLayeredPane.DEFAULT_LAYER);

        jSplitPane1.setRightComponent(lpnDetallesCaso);

        javax.swing.GroupLayout pnlDetallesCasoLayout = new javax.swing.GroupLayout(pnlDetallesCaso);
        pnlDetallesCaso.setLayout(pnlDetallesCasoLayout);
        pnlDetallesCasoLayout.setHorizontalGroup(
            pnlDetallesCasoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jSplitPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 389, javax.swing.GroupLayout.PREFERRED_SIZE)
        );
        pnlDetallesCasoLayout.setVerticalGroup(
            pnlDetallesCasoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jSplitPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 352, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lblAnioEscolar)
                            .addComponent(lblFecha)
                            .addComponent(lblReferimiento))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel2Layout.createSequentialGroup()
                                .addComponent(txtReferimiento, javax.swing.GroupLayout.PREFERRED_SIZE, 269, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btnBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(4, 4, 4)
                                .addComponent(lblReferimientoValMarker))
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel2Layout.createSequentialGroup()
                                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                    .addComponent(ftfAnioEscolar, javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(ftfFecha, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(lblFechaValMarker)
                                    .addComponent(lblAnioEscolarValMarker)))))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(lblEstadoCaso)
                        .addGap(19, 19, 19)
                        .addComponent(cmbEstadoCaso, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
            .addComponent(pnlDetallesCaso, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lblFecha)
                            .addComponent(ftfFecha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(lblFechaValMarker))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lblAnioEscolar)
                            .addComponent(ftfAnioEscolar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(lblAnioEscolarValMarker))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(btnBuscar, 0, 0, Short.MAX_VALUE)
                            .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(txtReferimiento)
                                .addComponent(lblReferimiento, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE))))
                    .addComponent(lblReferimientoValMarker))
                .addGap(18, 18, 18)
                .addComponent(pnlDetallesCaso, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cmbEstadoCaso, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblEstadoCaso))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(statusPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(267, Short.MAX_VALUE)
                .addComponent(btnAceptar)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(btnCancelar)
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(14, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnAceptar, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(statusPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void lstDetallesCasoValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_lstDetallesCasoValueChanged
        // TODO add your handling code here:
        int selectedOption = lstDetallesCaso.getSelectedIndex();
        switch (selectedOption) {
            case 0:
                lpnDetallesCaso.moveToFront(pnlAnalisisResPruebas);
                break;
            case 1:
                lpnDetallesCaso.moveToFront(pnlJuicioClinico);
                break;
            case 2:
                lpnDetallesCaso.moveToFront(pnlDiagnostico);
                break;
            case 3:
                lpnDetallesCaso.moveToFront(pnlTratamiento);
                break;
            case 4:
                lpnDetallesCaso.moveToFront(pnlResumenEvolucion);
                break;
            case 5:
                lpnDetallesCaso.moveToFront(pnlRecomendaciones);
                break;
        }
    }//GEN-LAST:event_lstDetallesCasoValueChanged
    
    private void btnAceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAceptarActionPerformed
        // TODO add your handling code here:
        // TODO: implementar correctamente el spinning progress bar
        ProgressCircle pc = new ProgressCircle(statusAnimationLabel);
        String trabajoCompletoMensaje = "Caso registrado exitosamente.";
        pc.start();
        if (!checkFormFields()) {
            statusMessageLabel.setText("Por favor corriga los campos marcados.");
            statusMessageLabel.setForeground(Color.red);
            new Thread(new LabelToolTipShower(statusMessageLabel, 3000)).start();
            return;
        }
        
        if (txaJuicioClinico.getText().isEmpty()) {
            statusMessageLabel.setText("El campo juicio clinico no puede estar vacio");
            statusMessageLabel.setForeground(Color.red);
            statusMessageLabel.setVisible(true);
            lpnDetallesCaso.moveToFront(pnlJuicioClinico);
            return;
        }

        // si todo esta bien
        statusMessageLabel.setVisible(false);
        String accion = null;
        try {
            if (modo != null && modo.equals(RegistroEdicionModo.REGISTRO)) {
                // creando el objeto referimiento
                accion = "crear";
                Caso caso = new Caso(null, DateUtils.parseDate(ftfFecha.getText()), ftfAnioEscolar.getText(), txaJuicioClinico.getText(),
                        (rbnDiagDefSi.isSelected() ? 'S' : 'N'), cmbEstadoCaso.getSelectedItem().toString().charAt(0));
                caso.setReferimiento(referimientoCaso);
                caso.setCsoAnalisisResultadosPruebas((!txaAnalisisResPruebas.getText().isEmpty() ? txaAnalisisResPruebas.getText() : null));
                caso.setCsoDiagnostico((!txaDiagnostico.getText().isEmpty() ? txaDiagnostico.getText() : null));
                caso.setCsoTratamiento((!txaTratamiento.getText().isEmpty() ? txaTratamiento.getText() : null));
                caso.setCsoResumenEvolucion((!txaResumenEvolucion.getText().isEmpty() ? txaResumenEvolucion.getText() : null));
                caso.setCsoRecomendaciones((!txaRecomendaciones.getText().isEmpty() ? txaRecomendaciones.getText() : null));
                
                jpaCasoDao.persist(caso);
            } else if (modo != null && modo.equals(RegistroEdicionModo.EDICION)) {
                if (casoAEditar == null) {
                    throw new Exception("El caso a editar no ha sido establecido");
                }
                accion = "editar";
                trabajoCompletoMensaje = trabajoCompletoMensaje.replace("registrado", "editado");
                
                casoAEditar.setCsoFecha(DateUtils.parseDate(ftfFecha.getText()));
                casoAEditar.setCsoAnioEscolar(ftfAnioEscolar.getText());
                casoAEditar.setCsoJuicioClinico(txaJuicioClinico.getText());
                casoAEditar.setCsoDiagnosticoDefinitivo((rbnDiagDefSi.isSelected() ? 'S' : 'N'));
                casoAEditar.setCsoEstadoCaso(cmbEstadoCaso.getSelectedItem().toString().charAt(0));
                casoAEditar.setCsoAnalisisResultadosPruebas((!txaAnalisisResPruebas.getText().isEmpty() ? txaAnalisisResPruebas.getText() : null));
                casoAEditar.setCsoDiagnostico((!txaDiagnostico.getText().isEmpty() ? txaDiagnostico.getText() : null));
                casoAEditar.setCsoTratamiento((!txaTratamiento.getText().isEmpty() ? txaTratamiento.getText() : null));
                casoAEditar.setCsoResumenEvolucion((!txaResumenEvolucion.getText().isEmpty() ? txaResumenEvolucion.getText() : null));
                casoAEditar.setCsoRecomendaciones((!txaRecomendaciones.getText().isEmpty() ? txaRecomendaciones.getText() : null));
                
                jpaCasoDao.update(casoAEditar);
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, String.format("<html><p>Error al " + accion + " registro de caso<br /><br />%s</p></html>",
                    e.getMessage()), "Caso", JOptionPane.ERROR_MESSAGE);
            return;
        }
        
        statusMessageLabel.setText(trabajoCompletoMensaje);
        statusMessageLabel.setForeground(Color.GREEN);
        statusMessageLabel.setVisible(true);
        new Thread(new LabelToolTipShower(statusMessageLabel, 3500)).start();
        LimpiadorComponentes.limpiarComponentes(this);
        ftfFecha.requestFocusInWindow();
        pc.stop();
    }//GEN-LAST:event_btnAceptarActionPerformed
    
    private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
        // TODO add your handling code here:
        this.dispose();
    }//GEN-LAST:event_btnCancelarActionPerformed
    
    private void btnBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBuscarActionPerformed
        // TODO add your handling code here:
        BusquedaRapida brr = new BusquedaRapida(this, true);
        brr.setTitle("Buscar Referimiento");
        brr.setEntitySearcher(new EntitySearcher.ReferimientoBasicEntitySearcher());
        brr.getLblEntidades().setText("Referimientos");
        brr.setLocationRelativeTo(this);
        brr.setVisible(true);
        
        Object refId = brr.getEntitySelectedId();
        if (refId != null) {
            referimientoCaso = new ReferimientoJpaDao().findById(refId);
            txtReferimiento.setText(referimientoCaso.toString());
        }
    }//GEN-LAST:event_btnBuscarActionPerformed
    
    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
        // TODO add your handling code here:
        statusMessageLabel.setVisible(false);
        statusAnimationLabel.setVisible(false);
        Date currDate = new Date();
        ftfFecha.setText(String.format("%1$td%1$tm%1$tY", currDate));
        Integer year = new Integer(String.format("%tY", currDate));
        ftfAnioEscolar.setText(year.toString() + (year + 1));
        
        if (modo != null && modo.equals(RegistroEdicionModo.EDICION)) {
            btnBuscar.setEnabled(false);
            txtReferimiento.setText(casoAEditar.getReferimiento().toString());
            txaAnalisisResPruebas.setText(casoAEditar.getCsoAnalisisResultadosPruebas() != null ? casoAEditar.getCsoAnalisisResultadosPruebas() : "");
            txaJuicioClinico.setText(casoAEditar.getCsoJuicioClinico());
            txaDiagnostico.setText(casoAEditar.getCsoDiagnostico() != null ? casoAEditar.getCsoDiagnostico() : "");
            if (casoAEditar.getCsoDiagnosticoDefinitivo() == 'S') {
                rbnDiagDefSi.setSelected(true);
            } else {
                rbnDiagDefNo.setSelected(true);
            }
            txaTratamiento.setText(casoAEditar.getCsoTratamiento() != null ? casoAEditar.getCsoTratamiento() : "");
            txaResumenEvolucion.setText(casoAEditar.getCsoResumenEvolucion() != null ? casoAEditar.getCsoResumenEvolucion() : "");
            txaRecomendaciones.setText(casoAEditar.getCsoRecomendaciones() != null ? casoAEditar.getCsoRecomendaciones() : "");
            cmbEstadoCaso.setSelectedIndex(casoAEditar.getCsoEstadoCaso() == 'A' ? 0 : (casoAEditar.getCsoEstadoCaso() == 'C' ? 1 : 2));
        }
        lpnDetallesCaso.moveToFront(pnlAnalisisResPruebas);
    }//GEN-LAST:event_formWindowOpened

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Windows".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(RegistroEdicionCaso.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(RegistroEdicionCaso.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(RegistroEdicionCaso.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(RegistroEdicionCaso.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            
            public void run() {
                new RegistroEdicionCaso().setVisible(true);
            }
        });
    }
    
    private boolean checkFormFields() {
        LimpiadorComponentes.limpiarValidationMarkers(this);
        boolean validFields = true;
        
        FieldValidator emptynessVal, dateVal;
        emptynessVal = new EmptyFieldValidator();
        dateVal = new DateFieldValidator();
        
        FieldValidator[] emptynessArr = new FieldValidator[]{emptynessVal};
        
        HashMap<JLabel, FieldValidator[]> campos = new HashMap<JLabel, FieldValidator[]>();
        campos.put(lblFechaValMarker, new FieldValidator[]{emptynessVal, dateVal});
        campos.put(lblAnioEscolarValMarker, emptynessArr);
        campos.put(lblReferimientoValMarker, emptynessArr);
        
        validFields = FormFieldValidator.verifyFormFields(campos);
        
        if (txaJuicioClinico.getText().isEmpty()) {
            JOptionPane.showMessageDialog(this, "El campo juicio clinico no puede estar vacio", "Caso", JOptionPane.ERROR_MESSAGE);            
            validFields &= false;
        }
        
        return validFields;
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.ButtonGroup bgpDefinitivo;
    private javax.swing.JButton btnAceptar;
    private javax.swing.JButton btnBuscar;
    private javax.swing.JButton btnCancelar;
    private javax.swing.JComboBox cmbEstadoCaso;
    private javax.swing.JFormattedTextField ftfAnioEscolar;
    private javax.swing.JFormattedTextField ftfFecha;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JScrollPane jScrollPane5;
    private javax.swing.JScrollPane jScrollPane6;
    private javax.swing.JScrollPane jScrollPane7;
    private javax.swing.JSplitPane jSplitPane1;
    private javax.swing.JLabel lblAnioEscolar;
    private javax.swing.JLabel lblAnioEscolarValMarker;
    private javax.swing.JLabel lblEstadoCaso;
    private javax.swing.JLabel lblFecha;
    private javax.swing.JLabel lblFechaValMarker;
    private javax.swing.JLabel lblReferimiento;
    private javax.swing.JLabel lblReferimientoValMarker;
    private javax.swing.JLayeredPane lpnDetallesCaso;
    private javax.swing.JList lstDetallesCaso;
    private javax.swing.JPanel pnlAnalisisResPruebas;
    private javax.swing.JPanel pnlDefinitivo;
    private javax.swing.JPanel pnlDetallesCaso;
    private javax.swing.JPanel pnlDiagnostico;
    private javax.swing.JPanel pnlJuicioClinico;
    private javax.swing.JPanel pnlRecomendaciones;
    private javax.swing.JPanel pnlResumenEvolucion;
    private javax.swing.JPanel pnlTratamiento;
    private javax.swing.JRadioButton rbnDiagDefNo;
    private javax.swing.JRadioButton rbnDiagDefSi;
    private javax.swing.JLabel statusAnimationLabel;
    private javax.swing.JLabel statusMessageLabel;
    private javax.swing.JPanel statusPanel;
    private javax.swing.JTextArea txaAnalisisResPruebas;
    private javax.swing.JTextArea txaDiagnostico;
    private javax.swing.JTextArea txaJuicioClinico;
    private javax.swing.JTextArea txaRecomendaciones;
    private javax.swing.JTextArea txaResumenEvolucion;
    private javax.swing.JTextArea txaTratamiento;
    private javax.swing.JTextField txtReferimiento;
    // End of variables declaration//GEN-END:variables
}
